package pl.un4giv3n.mightvsmagic.action.clan;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import pl.un4giv3n.mightvsmagic.action.PersistenceAction;
import pl.un4giv3n.mightvsmagic.entity.Clan;
import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.utils.ClanUtil;
import pl.un4giv3n.mightvsmagic.utils.ImageUtil;

public abstract class ClanAction extends PersistenceAction{

	private static final long serialVersionUID = 1L;
	protected static final int MAX_ALTAR_LEVEL = 5;
	protected static final int MAX_TOWER_LEVEL = 10;
	protected static final int MAX_BARRACKS_LEVEL = 10;
	protected User user;
	protected Clan clan;
	
	public boolean isCanJoinClan(){
		return user.getClan() == null;
	}
	
	public boolean isCanLeaveClan(){
		return user.getClan() != null && clan != null && user.getClan().getId() == clan.getId();
	}
	
	public boolean isCanConfigClan(){
		return isCanLeaveClan() && (user.isClanAdmin() || user.isClanMod());
	}
	
	public boolean isClanAdmin(){
		return isCanLeaveClan() && user.isClanAdmin();
	}
	
	public boolean isHomeClan(){
		return user.getClan() != null && clan != null && user.getClan().getId() == clan.getId();
	}

	public Clan getClan() {
		return clan;
	}
	
	public String getClanImage() {
		return ImageUtil.getClanImage(clan, getContext().getRealPath("/"));
	}
	
	public int getClanPendingUserCount(){
		EntityManager em = getEntityManager();
		Query query = em.createNamedQuery("find.user.pending.clan");
		query.setParameter("clanId", clan.getId());
		int result = query.getResultList().size();
		em.close();
		return result;
	}
	
	public String getClanBonus(){
		return ClanUtil.getClanBonusInfo(clan);
	}
	

	public String getAltarImprovementCost(){
		return ClanUtil.getAltarImprovementCost(clan) + " złota";
	}
	public String getTowerImprovementCost(){
		return ClanUtil.getTowerImprovementCost(clan) + " złota";
	}
	public String getBarracksImprovementCost(){
		return ClanUtil.getBarracksImprovementCost(clan) + " złota";
	}
	public long getMaxMageCount(){
		return ClanUtil.getMaxMageCount(clan);
	}
	public long getMaxKnightCount(){
		return ClanUtil.getMaxKnightCount(clan);
	}
	
	public boolean isCanImproveAltar(){
		return clan.getAltarLevel() < MAX_ALTAR_LEVEL;
	}
	public boolean isCanImproveBarracks(){
		return clan.getAltarLevel() < MAX_BARRACKS_LEVEL;
	}
	public boolean isCanImproveTower(){
		return clan.getAltarLevel() < MAX_TOWER_LEVEL;
	}
	
}
